let prodTools = {};

let store = window.localStorage;

// let prods = {}; //未来在localStorage中获取
// prods JSON字符串转换的对象Map
let prods = JSON.parse(store.getItem('prods') || '{}');

//增加或者追加 obj{id:XXX,num:YYY}
prodTools.addOrUpdate = function (obj) {
    //判断是否存在
    if (prods[obj.id]) {
        //追加
        prods[obj.id] += obj.num;
    } else {
        //新增
        prods[obj.id] = obj.num;
    }
    //保存
    this.saveProd(prods);
};

//删除
prodTools.delete = function (id) {
    delete  prods[id];
    //保存
    this.saveProd(prods);
};

//获取localStorage
prodTools.getProds = function () {
    return JSON.parse(store.getItem('prods') || '{}');
};

//获取总数
prodTools.getTotalCount = function () {
    let sum = 0;
    for (let id in prods) {
        sum += prods[id];
    }
    return sum;
};

//存储
prodTools.saveProd = function (prods) {
    store.setItem('prods', JSON.stringify(prods))
};

// //根据key获取值
// prodTools.getValueByKey = function(key){
//     return this.getProds[key];
// }

export default prodTools;


